package cn.tedu.ivos.geofence.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.geofence.mapper.GeofenceMapper;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceQuery;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceSaveParam;
import cn.tedu.ivos.geofence.pojo.entity.Geofence;
import cn.tedu.ivos.geofence.pojo.vo.GeofenceVO;
import cn.tedu.ivos.geofence.service.GeofenceService;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class GeofenceServiceImpl implements GeofenceService {
    @Autowired
    private GeofenceMapper geofenceMapper;
    @Autowired
    private VehicleMapper vehicleMapper;

    @Override
    public List<GeofenceVO> selectGeofence(GeofenceQuery geofenceQuery) {
        log.debug("查询围栏：传入参数={}"+geofenceQuery);
        List<GeofenceVO> list=geofenceMapper.selectGeofence(geofenceQuery);
        return list;
    }

    @Override
    public void updateStatus(Long geofenceId, String status) {
        log.debug("修改电子围栏状态：geofenceId={},status={}", geofenceId, status);
        Geofence geofence = new Geofence();
        geofence.setId(geofenceId);
        geofence.setStatus(status);
        geofence.setUpdateTime(new Date());
        geofenceMapper.updateStatus(geofence);
    }

    @Override
    public void deleteGeo(Long geofenceId) {
        log.debug("删除电子围栏：geofenceId={}", geofenceId);
        /*删除时一定要根据业务设计方案:围栏上有关联的车辆数据*/
        //1.封装车辆的查询条件
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setGeofenceId(geofenceId);
        //2.调用车辆模块的查车方法
        List<Vehicle> vehicleList = vehicleMapper.selectVehicleBy(vehicleQuery);
        //3.如果该围栏下有绑定的车辆，无法删除，抛出异常
        if(vehicleList != null && vehicleList.size() > 0){
            throw new ServiceException(StatusCode.VEHICLE_EXISTS);
        }else{
            //4.如果没有绑定的车辆，可以直接删除
            geofenceMapper.deleteGeo(geofenceId);
        }
    }

    @Override
    public void saveGeo(GeofenceSaveParam geofenceSaveParam) {
        log.debug("新增电子围栏：传入参数={}", geofenceSaveParam);
        Geofence geofence = new Geofence();
        BeanUtils.copyProperties(geofenceSaveParam, geofence);
        geofence.setStatus("1");
        geofence.setCreateTime(new Date());
        geofenceMapper.insertGeo(geofence);
    }
}
